package com.hxk.es.service;

import com.alibaba.fastjson.JSON;
import com.hxk.es.bean.Good;
import com.hxk.es.utils.HttpParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class GoodService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public boolean addGoods(String goodName){

        BulkRequest bulkRequest = new BulkRequest("jd_index");
        try {
            List<Good> goods = HttpParseUtil.getGoodsByName(goodName);

            for (Good good : goods) {
                bulkRequest.add(new IndexRequest().source(JSON.toJSONString(good), XContentType.JSON));
            }

            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

            return !bulkResponse.hasFailures();
        }catch (Exception e){
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 获取数据
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public List<Map<String,Object>> getGoods(String keyword, int pageNo, int pageSize) throws Exception{

        if (pageNo < 1){
            pageNo = 1;
        }

        List<Map<String,Object>> goods = new ArrayList<>();

        //创建查询请求
        SearchRequest searchRequest = new SearchRequest("jd_index");

        //构建查询条件
        searchRequest.source(
                new SearchSourceBuilder()//创建一个查询构造器
                        .from(pageNo) //设置分页，当前页
                        .size(pageSize)//设置分页，当前页面显示条数
                        .query(QueryBuilders.termQuery("name", keyword))//获取一个精准查询
                        .timeout(new TimeValue(60, TimeUnit.SECONDS))//执行最大超时时长
        );

        //发送查询请求给es服务端，并获取相应结果
        SearchResponse searchResponse = this.restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //拿到响应结果
        SearchHit[] hits = searchResponse.getHits().getHits();

        //解析数据
        for (SearchHit hit : hits) {
            goods.add(hit.getSourceAsMap());
        }

        return goods;
    }

    /**
     * 获取带高亮的数据
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> searchHighlightGoods(String keyword, int pageNo, int pageSize) throws Exception{
        if (pageNo < 1){
            pageNo = 1;
        }

        List<Map<String,Object>> goods = new ArrayList<>();

        SearchRequest searchRequest = new SearchRequest("jd_index");

        searchRequest.source(new SearchSourceBuilder()
                .from(pageNo)
                .size(pageSize)
                .query(QueryBuilders.termQuery("name",keyword))
                .timeout(new TimeValue(60,TimeUnit.SECONDS))
                .highlighter(new HighlightBuilder()
                        .field("name")
                        .requireFieldMatch(true)
                        .preTags("<span style='color:red'>")
                        .postTags("</span>")
                )
        );

        SearchResponse searchResponse = this.restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //拿到响应结果
        SearchHit[] hits = searchResponse.getHits().getHits();

        //解析数据
        for (SearchHit hit : hits) {
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (name != null){
                Text[] fragments = name.fragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("name",n_title);
            }
            goods.add(sourceAsMap);
        }

        return goods;
    }
}
